import { createStore } from 'vuex'
import axios from 'axios'

export default createStore({
  state: {
    members: [],
    products: [],
    orders: [],
    currentMember: null,
    cartItems: []
  },
  mutations: {
    SET_MEMBERS(state, members) {
      state.members = members
    },
    SET_PRODUCTS(state, products) {
      state.products = products
    },
    SET_ORDERS(state, orders) {
      state.orders = orders
    },
    SET_CURRENT_MEMBER(state, member) {
      state.currentMember = member
    },
    ADD_TO_CART(state, item) {
      const existingItem = state.cartItems.find(cartItem => cartItem.productCode === item.productCode)
      if (existingItem) {
        existingItem.quantity += item.quantity
      } else {
        state.cartItems.push(item)
      }
    },
    REMOVE_FROM_CART(state, productCode) {
      state.cartItems = state.cartItems.filter(item => item.productCode !== productCode)
    },
    UPDATE_CART_ITEM_QUANTITY(state, { productCode, quantity }) {
      const item = state.cartItems.find(item => item.productCode === productCode)
      if (item) {
        item.quantity = quantity
      }
    },
    CLEAR_CART(state) {
      state.cartItems = []
    }
  },
  actions: {
    async fetchMembers({ commit }) {
      try {
        const response = await axios.get('/api/members')
        commit('SET_MEMBERS', response.data)
      } catch (error) {
        console.error('获取会员列表失败:', error)
      }
    },
    async fetchProducts({ commit }) {
      try {
        const response = await axios.get('/api/products')
        commit('SET_PRODUCTS', response.data)
      } catch (error) {
        console.error('获取商品列表失败:', error)
      }
    },
    async fetchOrders({ commit }) {
      try {
        const response = await axios.get('/api/orders')
        commit('SET_ORDERS', response.data)
      } catch (error) {
        console.error('获取订单列表失败:', error)
      }
    },
    async searchMemberByCard({ commit }, cardNumber) {
      try {
        const response = await axios.get(`/api/members/card/${cardNumber}`)
        commit('SET_CURRENT_MEMBER', response.data)
        return response.data
      } catch (error) {
        commit('SET_CURRENT_MEMBER', null)
        return null
      }
    }
  },
  getters: {
    cartTotal: (state) => {
      return state.cartItems.reduce((total, item) => {
        return total + (item.unitPrice * item.quantity)
      }, 0)
    },
    cartItemCount: (state) => {
      return state.cartItems.length
    }
  }
}) 